//
//  OneViewController.swift
//  Retail
//
//  Created by zhangjikuan on 2020/6/29.
//  Copyright © 2020 aqdeal. All rights reserved.
//

import UIKit
import Alamofire
import SnapKit
import HandyJSON
import Kingfisher
func JSONModel<T>(_ type: T.Type, withKeyValues data:[String:Any]) throws -> T where T: Decodable {
    let jsonData = try JSONSerialization.data(withJSONObject: data, options: [])
    let model = try JSONDecoder().decode(type, from: jsonData)
    return model
}

class BaseResponse<T: HandyJSON>: HandyJSON {
    var status : Int?
    var message: String?
    var data: T?
    public required init(){}
}


class Model: NSObject, HandyJSON {
    
    var data:Dictionary<String, Any>?
    
    required override init() {
        
    }
}

class DataModel: NSObject, HandyJSON {
    
    var list:Array<Any>?
    
    required override init() {
        
    }
}


class Person: NSObject, HandyJSON {
    var descriptions: String?
    var headimg: String?
    var id:Int?
    var name :String?

    required override init() {
        
    }
}

class OneViewController: BaseViewController {
    var sectionList:[Array<Any>] = []
    
    var dataList:[Person] = []
    var tableView: UITableView!
    var otherTabl:UITableView?
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "One"
     
        initDatas()
     
        initSubViews()
        
        getRequest()
        
    }
    
    // MARK: -Actions
    func loginClick() {
        
        
        let ctr = LoginViewController()
        
        //        present(ctr, animated: true, completion: nil)
    
        RetailToolChangeRootController.execute(ctr)
     
    }
    
    func showWeb() {
        let webCtr = WebViewController()
        webCtr.urlString = "https://www.jianshu.com/p/2eca8c29db27";
        webCtr.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(webCtr, animated: true)
    }
    
    func initDatas()  {

        sectionList.append(["登录 Action"])
        sectionList.append(["WebView Action"])
        sectionList.append(self.dataList)
        
    }
    
    
    /// 初始化子视图
    func initSubViews() {
        tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.bottom.left.right.equalToSuperview()
        }
    }

    func getRequest() {
        let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list"
//        AF.request(urlStr).responseJSON { (response) in
//            switch response.result {
//            case .success(let json):
//                print(json)
//                break
//            case .failure(let error):
//                print("error:\(error)")
//                break
//            }
//        }

        AF.request(urlStr, method: .post, parameters: ["name":"hibo","password":"123456"]).responseJSON { (response) in
            switch response.result {
            case .success(let json):
                print(json)
                self.dataList.removeAll()
                self.sectionList .remove(at: 2)
        
                if let obj = Model.deserialize(from: json as? Dictionary) {
                    print(obj.data as Any)
                    if let data = DataModel.deserialize(from: obj.data) {
                        print(data)
                        for i in 1...data.list!.count {
                            print(data.list![i-1])
                            let dict:Dictionary = data.list![i-1] as! Dictionary<String, Any>
                            let persion = Person.deserialize(from: data.list![i-1] as? Dictionary)
                            persion?.descriptions = (dict["description"] as! String)
                            self.dataList.append(persion!)
                            
                        }
                        self.sectionList.append(self.dataList)
                        self.tableView.reloadData()
                    }
                }
                break
            case .failure(let error):
                print("error:\(error)")
                break
            }
        }
    }

}

extension OneViewController: UITableViewDelegate
{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.section {
        case 0:
            loginClick()
        case 1:
            showWeb()
        default:
            print(String(indexPath.row))
            let detail = GoodsDetailViewController()
            detail.person = self.dataList[indexPath.row]
            detail.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(detail, animated: true)
        }
  
        
    }
}

extension OneViewController: UITableViewDataSource
{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        switch section {
        case 0:
            return 1
        case 1:
            return 1
        case 2:
            if self.dataList.count == 0 {
                return 0
            } else{
                return self.dataList.count
            }
        default:
            return 0
        }

    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        switch indexPath.section {
        case 0:
            var cell = tableView.dequeueReusableCell(withIdentifier: "cellOne")
            if cell == nil {
                cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellOne")
            }
            let section0 = self.sectionList[0]
            let name = section0[indexPath.row] as! String
            cell?.textLabel?.text = name
            return cell!
            
        case 1:
            var cell = tableView.dequeueReusableCell(withIdentifier: "cellOne1")
            if cell == nil {
                cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellOne1")
            }
            let section1 = self.sectionList[1]
            let name = section1[indexPath.row] as! String
            cell?.textLabel?.text = name
            return cell!
            
        default:
            var cell = tableView.dequeueReusableCell(withIdentifier: "cellOne2")
            if cell == nil {
                cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellOne2")
            }
            let person = self.dataList[indexPath.row]
            cell?.textLabel?.text = person.name
            cell?.detailTextLabel?.text = person.descriptions
            cell?.imageView?.kf.setImage(with: URL(string: person.headimg!))
            return cell!
            
        }
    
        
    }
    
    
}

